﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Media;
using MaterialDesignColors;

namespace SvgViewer.Utilities;

internal class BackgroundManager
{
    public static readonly BackgroundManager Instance = new();
    private                List<Geometry>    backgrounds;
    private                List<Color>       backgroundColors;

    public IReadOnlyList<Geometry> Backgrounds {
        get {
            if (backgrounds == null)
            {
                LoadBackgrounds();
            }

            return backgrounds;
        }
    }

    public IReadOnlyList<Color> BackgroundColors {
        get {
            if (backgroundColors == null)
            {
                LoadBackgroundColors();
            }

            return backgroundColors;
        }
    }


    private void LoadBackgrounds()
    {
        backgrounds = new List<Geometry> {
            Geometry.Parse("")
        };
        using (var fs = new FileStream(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Backgrounds.tmp"),
                   FileMode.Open, FileAccess.Read))
        {
            using (var sr = new StreamReader(fs, Encoding.UTF8))
            {
                while (sr.Peek() >= 0)
                {
                    var source = $"{sr.ReadLine()}".TrimStart(' ');

                    if (string.IsNullOrEmpty(source)                               == false &&
                        source.IndexOf("<!--", StringComparison.OrdinalIgnoreCase) == -1)
                    {
                        try
                        {
                            var geometry = Geometry.Parse(source);
                            if (geometry.Bounds != Rect.Empty)
                            {
                                backgrounds.Add(geometry);
                            }
                        }
                        catch
                        {
                            // ignored
                        }
                    }
                }
            }
        }
    }

    private void LoadBackgroundColors()
    {
        backgroundColors = new List<Color>();
        foreach (var swatch in SwatchHelper.Swatches)
        {
            backgroundColors.Add(swatch.Hues.ToList()[5]);
        }
    }
}